package com.xyhy.starter.web.advice;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.xyhy.core.web.model.wrapper.Result;
import com.xyhy.core.web.model.wrapper.ResultCode;

import jakarta.servlet.http.HttpServletResponse;

/**
 * @author Fire Team - Robert
 * @Description 异常处理类，可参见 ResponseEntityExceptionHandler。
 * @date 2020年12月15日
 */
@Slf4j
@RestControllerAdvice
public class ShiroExceptionAdvice extends ExceptionAdvice {

  @ExceptionHandler(value = UnauthenticatedException.class)
  public Result<Object> unauthenticatedExceptionHandler(UnauthenticatedException ex, HttpServletResponse response) {
    log.error("unauthenticatedExceptionHandler", ex);
    return Result.fail(ResultCode.UN_AUTHORIZED, ex);
  }

  @ExceptionHandler(value = AuthorizationException.class)
  public Result<Object> authorizationExceptionHandler(AuthorizationException ex, HttpServletResponse response) {
    log.error("authorizationExceptionHandler", ex);
    return Result.fail(ResultCode.FORBIDDEN, ex);
  }

  @ExceptionHandler(value = AuthenticationException.class)
  public Result<Object> aaaHandler(AuthenticationException ex, HttpServletResponse response) {
    log.error("exceptionHandler", ex);
    return Result.fail(ResultCode.INTERNAL_SERVER_ERROR, ex);
  }

  @ExceptionHandler(value = ShiroException.class)
  public Result<Object> shiroExceptionHandler(ShiroException ex, HttpServletResponse response) {
    log.error("exceptionHandler", ex);
    return Result.fail(ResultCode.AUTHENTICATE_ERROR, ex);
  }

}
